package org.example;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

/**
 * @author TonySong
 * @date 2025/7/30 0030
 * @time 15:18
 */
public class Test3 {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {

//        User user =new User();
//        user.sex ="男";
//        user.sex="女";
        Class<User> userClass = User.class;
//        User user = userClass.newInstance();//调用默认构造创建对象
        User user = userClass.getConstructor(null).newInstance();

        //上面的两行代码：User user=new User();
        Field sex = userClass.getDeclaredField("sex");
        Object o = sex.get(user);//获取属性的值 null
        System.out.println(o);
        sex.set(user,"男");//user.setSex("男")
        System.out.println(sex.get(user).toString());
        //修改private级别的属性
        Field age = userClass.getDeclaredField("age");
        age.setAccessible(true);//打开访问级别（false）
        System.out.println(age.get(user));//报错：private级别的属性不能访问
        age.set(user,22);
        System.out.println(age.get(user));//user.getAge()
//
//        Constructor<?>[] constructors = userClass.getDeclaredConstructors();
//        for(Constructor constructor: constructors){
//            System.out.println("构造器名："+constructor.getName()+
//                    "访问级别："+ Modifier.toString(constructor.getModifiers()));
//        }
    }
}
